<template>
    <!--引用表格-->
   <BasicTable @register="registerTable" :rowSelection="rowSelection">
     <!--插槽:table标题-->
      <template #tableTitle>
          <a-button type="primary" v-auth="'demand:cgcj_demand_plan:add'"  @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
          <a-button  type="primary" v-auth="'demand:cgcj_demand_plan:exportXls'"  preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
          <j-upload-button  type="primary" v-auth="'demand:cgcj_demand_plan:importExcel'"  preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
          <a-dropdown v-if="selectedRowKeys.length > 0">
              <template #overlay>
                <a-menu>
                  <a-menu-item :disabled="batchDelDisabled" key="1" @click="batchHandleDelete">
                    <Icon icon="ant-design:delete-outlined"></Icon>
                    删除
                  </a-menu-item>
                </a-menu>
              </template>
              <a-button v-auth="'demand:cgcj_demand_plan:deleteBatch'">批量操作
                <Icon icon="mdi:chevron-down"></Icon>
              </a-button>
        </a-dropdown>
        <!-- 高级查询 -->
        <super-query :config="superQueryConfig" @search="handleSuperQuery" />
      </template>
       <!--操作栏-->
      <template #action="{ record }">
        <TableAction divider :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
      </template>
      <!--字段回显插槽-->
      <template v-slot:bodyCell="{ column, record, index, text }">
      </template>
    </BasicTable>
    <!-- 表单区域 -->

  <BasicModal
      v-bind="$attrs"
      wrapClassName="approval-form-modal"
      :destroyOnClose="true"
      :footer="null"
      :title="approvalModal.title"
      :width="896"
      :canFullscreen="true"
      :defaultFullscreen="true"
      @register="registerApprovalModal"
    >
      <CgcjDemandPlanApproval
        :isInModal="true"
        :formBpm="false"
        :formDisabled="approvalModal.disabled"
        :recordId="approvalModal.recordId"
        :processInstanceId="approvalModal.processInstanceId"
        :processStatus="approvalModal.processStatus"
        :operate="approvalModal.operate"
        :isApprovalNew="approvalModal.isApprovalNew"
        @success="handleSuccess"
        :isUpdate="isUpdate"
      ></CgcjDemandPlanApproval>
    </BasicModal>
</template>

<script lang="ts" name="demand-cgcjDemandPlan" setup>
  import {ref, reactive, computed, unref} from 'vue';
  import {BasicTable, useTable, TableAction} from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import {useModal} from '/@/components/Modal';
  import CgcjDemandPlanModal from './components/CgcjDemandPlanModal.vue'
  import {columns, searchFormSchema, superQuerySchema} from './CgcjDemandPlan.data';
  import {list, deleteOne, batchDelete, getImportUrl,getExportUrl} from './CgcjDemandPlan.api';
  import {downloadFile} from '/@/utils/common/renderUtils';
  import { useUserStore } from '/@/store/modules/user';
  import { BasicModal } from '/@/components/Modal';
  import CgcjDemandPlanApproval from './CgcjDemandPlanApproval.vue';
  import { usePermission } from '/@/hooks/web/usePermission';

  const { hasPermission } = usePermission();
  const deletePermission = computed(() => hasPermission('demand:cgcj_demand_plan:delete'));
  const editPermission = computed(() => hasPermission('demand:cgcj_demand_plan:edit'));


  const isUpdate = ref(false);

    const approvalModal = ref<any>({
      title: '新增',
      operate: '',
      recordId: '',
      processInstanceId: '',
      processStatus: '',
      disabled: false,
      isApprovalNew: 0
    });
  const queryParam = reactive<any>({});
  const checkedKeys = ref<Array<string | number>>([]);
  const userStore = useUserStore();
  //注册model
  const [registerApprovalModal, { openModal, closeModal }] = useModal();
   //注册table数据
  const { prefixCls,tableContext,onExportXls,onImportXls } = useListPage({
      tableProps:{
           title: '需求计划',
           api: list,
           columns,
           canResize:false,
           formConfig: {
                //labelWidth: 120,
                schemas: searchFormSchema,
                autoSubmitOnEnter:true,
                showAdvancedButton:true,
                fieldMapToNumber: [
                ],
                fieldMapToTime: [
                ],
            },
           actionColumn: {
              // width: 120,
              // fixed:'right'
           },
           beforeFetch: (params) => {
             return Object.assign(params, queryParam);
           },
        },
        exportConfig: {
            name:"需求计划",
            url: getExportUrl,
            params: queryParam,
        },
        importConfig: {
            url: getImportUrl,
            success: handleSuccess,
        },
    });

  const [registerTable, {reload},{ rowSelection, selectedRowKeys, selectedRows }] = tableContext;

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }

   /**
    * 新增事件
    */
  function handleAdd() {
    approvalModal.value.title = '新增'
    approvalModal.value.operate = 'create'
    approvalModal.value.disabled = false
    approvalModal.value.recordId = ''
    approvalModal.value.processInstanceId = ''
    approvalModal.value.processStatus = ''
    approvalModal.value.taskId = ''
    approvalModal.value.isApprovalNew = new Date().getTime()
    isUpdate.value = true;
     openModal(true, {
       isUpdate: true,
       showFooter: true,
     });
  }
   /**
    * 编辑事件
    */
  function handleEdit(record: Recordable) {
    approvalModal.value.title = '编辑'
    approvalModal.value.operate = 'edit'
    approvalModal.value.disabled = false
    approvalModal.value.recordId = record.id
    approvalModal.value.processInstanceId = record.processInstanceId
    approvalModal.value.processStatus = record.processStatus
    approvalModal.value.isApprovalNew = new Date().getTime()
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: true,
     });
   }
   /**
    * 详情
   */
  function handleDetail(record: Recordable) {
    approvalModal.value.title = '查看'
    approvalModal.value.operate = 'view'
    approvalModal.value.disabled = true
    approvalModal.value.recordId = record.id
    approvalModal.value.processInstanceId = record.processInstanceId
    approvalModal.value.processStatus = record.processStatus
    approvalModal.value.isApprovalNew = new Date().getTime()
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: false,
     });
   }
   /**
    * 删除事件
    */
  async function handleDelete(record) {
     await deleteOne({id: record.id}, handleSuccess);
   }
  // 批量删除按钮状态
  const batchDelDisabled = computed(() => {
    let disabled = selectedRows.value.some((item: any) => {
      return item.processStatus !== 'DRAFT';
    });
    if (!disabled) {
      disabled = !deletePermission.value;
    }
    return disabled;
  });
   /**
    * 批量删除事件
    */
  async function batchHandleDelete() {
     await batchDelete({ids: selectedRowKeys.value},handleSuccess);
   }
   /**
    * 成功回调
    */
  function handleSuccess() {
    closeModal();
      (selectedRowKeys.value = []) && reload();
   }
   /**
    * 操作栏
    */
   function editBtnDisabled(record: any) {
    let disabled = record.processStatus !== 'DRAFT'
    if(!disabled){
      const userId = userStore.getUserInfo.id
      if(userId !== record.createBy){
        disabled = true
      }
    }
    if(!disabled){
       disabled = !editPermission.value
    }
    return disabled
  }
  function getTableAction(record){
       return [
         {
           label: '编辑',
           onClick: handleEdit.bind(null, record),
        color: 'success',
        disabled: editBtnDisabled(record),
        useConfirmButton: false,
           auth: 'demand:cgcj_demand_plan:edit',
         }
       ]
   }


  /**
   * 下拉操作栏
   */
  function getDropDownAction(record){
    return [
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
        color: 'info',
        type: 'link',
        size: 'small',
        useConfirmButton: false,
      }, {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft'
        },
        disabled: record.processStatus !== 'DRAFT',
        type: 'link',
        size: 'small',
        color: 'error',
        useConfirmButton: true,
        auth: 'demand:cgcj_demand_plan:delete'
      }
    ]
  }


</script>

<style lang="less" scoped>
  :deep(.ant-picker),
  :deep(.ant-input-number) {
  width: 100%;
  }

  :deep(.basictable-sidebar) {
  height: calc(100vh - 40px - 60px - 64px - 36px);
  }


  .approval-form-modal {
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
  width: 100%;
  }

  :deep(.ant-calendar-picker) {
  width: 100%;
  }
  }</style>